<?php

namespace App\Console\Commands;

use App\Model\Order;
use App\Model\PushOrder;
use Illuminate\Console\Command;

class CallRoute extends Command
{
    //品盛
    private $url = "http://openapi.fulu.com/api/getway";
//    private $app_key = "YZ2Fu5Y86kfnF4qIcKCtOK9PjJzlv4w7kq+bPPu0SmeZxjqn5gUBgTAthCnxFOXP";
//    private $app_secret = "10888069844749068c5f6fe742796e0b";

    //竹清网络
    private $app_key = "5aN/mSAIt3TKzydo+CETbqGduinUqPfksmCm60034GyF2S8su68+au0Dr3uJa31F";
    private $app_secret = "2f887bdc2f5b4151b8b06d52a628a52b";

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'getOrder {param}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function curlGet($url,$method,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } elseif ($method == 'get') {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        set_time_limit(0); //解除PHP脚本时间限制
        ini_set('memory_limit', '-1'); //修改内存值
        $flag =  $this->argument('param');
        if($flag == 'true'){
            $this->info('开启接单');
        }else{
            $this->info('参数不正确,停止接单');
            $flag = false;
        }
        $num = 0;
        $GoodsAllocated = 'DyWb';
        $sign = strtoupper(md5($GoodsAllocated."2Serge#57$768rtv0"));
        $data = "guaji=".$GoodsAllocated."&ts=2&Sign=".$sign;
        $url = "http://interface.qsios.cn:8136/actionapi/Order/GetOrderRedis";
//        $url = "http://localhost:8000/home/index/info";
        while($flag){
            $res = $this->curlGet($url,'post',$data);
//            $res = $this->curlGet($url,'get');
            if($res != "<Orders></Orders>"){
                $xml=simplexml_load_string($res);
                if(isset($xml->Order)){
                    $order = [];
                    $order['orderno'] = $xml->Order->OrderNo;
                    $order['status'] = $xml->Order->OrderStatus;
                    $order['buytime'] = strtotime($xml->Order->BuyTime);
                    $order['num'] = $xml->Order->BuyNum;
                    $ordernum = $order['num'];
                    $order['productid'] = $xml->Order->ProductId;
                    $order['productprice'] = $xml->Order->ProductPrice;
                    $order['productname'] = $xml->Order->ProductName;
                    $order['producttype'] = $xml->Order->ProductType;
                    $order['templateid'] = $xml->Order->TemplateId;
                    $order['chargeaccount'] = $xml->Order->ChargeAccount;
//                    $order['chargetype'] = $xml->Order->ChargeType;
                    $order['chargetype'] = 2;
                    $order['jsitid'] = $xml->Order->JSitid;
                    $order['gsitid'] = $xml->Order->GSitid;
                    $order['buyerip'] = $xml->Order->BuyerIp;
                    preg_match('/\d+/',$order['productname'],$price);
                    $price = $price[0];
                    $order['price'] = $price;
                    $order['remainingnumber'] = $price * $order['num'];
                    $order['customerorderno'] = $xml->Order->CustomerOrderNo;
                    $order['extractsignid'] = $xml->Order->ExtractSignId;
                    $url = 'http://asmile.cn:7006/order/'.$order['orderno'].'/'.$order['chargeaccount'].'/'.$order['remainingnumber'].'/'.$order['buyerip'];
                    $res = curlGet($url);
                    sleep(15);
                    $data = json_decode($res);
                    if(isset($data->url)){
                        $order['url'] = $data->url;
                    }else{
                        echo "获取短链接失败";
                    }
                    $orderInfo = Order::create($order);

                    $price = $order['remainingnumber'];
                    $order['num'] = 1;
                    $order['price'] = $price;
                    //是否拆分
                    switch ($price){
                        case 100:
                            PushOrder::create($order);
                            break;
                        case 200:
                            PushOrder::create($order);
                            break;
                        case 300:
                            PushOrder::create($order);
                            break;
                        case 500:
                            PushOrder::create($order);
                            break;
                        default:
                            $info['isok'] = 6;
                            Order::where('orderno',$order['orderno'])->update($info);
//                            switch ($orderPrice){
//                                case 100:
//                                    $product_id = 10707887;
//                                    break;
//                                case 200:
//                                    $product_id = 19016689;
//                                    break;
//                                case 300:
//                                    $product_id = 19016698;
//                                    break;
//                                case 500:
//                                    $product_id = 19016699;
//                                    break;
//                                case 1000:
//                                    $product_id = 19016700;
//                                    break;
//                            }
//                            $resFulu = $this->pushOrderFulu($product_id,$order['orderno'],$orderPrice,$ordernum);
//                            if($resFulu->code == 0){
//                                $infoFulu['branch'] = '已推送快充';
//                                $infoFulu['status'] = '已处理';
//                                $infoFulu['isok'] = 4;
//                                $infoFulu['bid'] = 888;
//                                $infoFulu['time'] = time();
//                                Order::where('orderno', $order['orderno'])->update($infoFulu);
//                            }else{
//                                $failInfo = '';
//                                switch ($resFulu->code){
//                                    case    2004:
//                                        $failInfo = "商户余额不足";
//                                        break;
//                                    case    3001:
//                                        $failInfo = "商品不存在或无法购买";
//                                        break;
//                                    case    3002:
//                                        $failInfo = "商品已下架";
//                                        break;
//                                    case    3003:
//                                        $failInfo = "商品维护中";
//                                        break;
//                                    case    3004:
//                                        $failInfo = "商品在维护期内";
//                                        break;
//                                    case    3005:
//                                        $failInfo = "商品库存不足";
//                                        break;
//                                    case    4004:
//                                        $failInfo = "充值账号在黑名单中";
//                                        break;
//                                    case    4010:
//                                        $failInfo = "外部订单号已存在";
//                                        break;
//                                }
//                                $infoFulu['branch'] = $resFulu->code.$failInfo;
//                                $infoFulu['status'] = '查询福禄失败原因';
//                                $infoFulu['isok'] = 3;
//                                $infoFulu['bid'] = 0;
//                                Order::where('orderno', $order['orderno'])->update($infoFulu);
//                            }
//                            if($ordernum > 1 && $price > 200) {
//                                $order['remainingnumber'] = $orderPrice;
//                                $order['pid'] = $orderInfo->id;
//                                for ($i = 0; $i < $ordernum; $i++) {
//                                    $order['orderno'] = $xml->Order->OrderNo . $i;
//                                    PushOrder::create($order);
//                                }
//                            }else{
//                                $order['remainingnumber'] = 500;
//                                $order['pid'] = $orderInfo->id;
//                                for ($i = 0;$i < $price / 500;$i++){
//                                    $order['orderno'] = $xml->Order->OrderNo.$i;
//                                    PushOrder::create($order);
//                                }
//                            }
                    }

                }else{
                    continue;
                    sleep(2);
                }
            }
            sleep(1);
        }
    }

    public function pushOrderFulu($product_id,$customer_order_no,$charge_account,$buy_num = 1){
        $param = [
            "product_id"    =>  $product_id,
            "customer_order_no"    =>  $customer_order_no,
            "charge_account"    =>  $charge_account,
            "buy_num"    =>  $buy_num
        ];

        $data = [
            "app_key"   =>  $this->app_key,
            "method"    =>  "fulu.order.direct.add",
            "timestamp" =>  date("Y-m-d H:i:s",time()),
            "version"   =>  "2.0",
            "format"    =>  "json",
            "charset"    =>  "utf-8",
            "sign_type"    =>  "md5",
            "app_auth_token"    =>  "",
            "biz_content"    =>  json_encode($param),
        ];
        $sign = $this->getSign($data);

        $data['sign'] = $sign;

        $res = $this->curlFulu($this->url,json_encode($data,JSON_UNESCAPED_SLASHES));

        $res = json_decode($res);

        return $res;

    }

    public function getSign($Parameters){
        //签名步骤一：把字典json序列化
        $json = json_encode( $Parameters, JSON_UNESCAPED_SLASHES);
        //签名步骤二：转化为数组
        $jsonArr = $this->mb_str_split( $json );
        //签名步骤三：排序
        sort( $jsonArr );
        //签名步骤四：转化为字符串
        $string = implode( '', $jsonArr );
        //签名步骤五：在string后加入secret
        $string = $string . $this->app_secret;
        //签名步骤六：MD5加密
        $result_ = strtolower( md5( $string ) );
        return $result_;
    }

    public function curlFulu($url,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function mb_str_split($str){
        return preg_split('/(?<!^)(?!$)/u', $str );
    }

}
